!(function($){
	"use strict";
	
	var Page = function() {
		this.$btnAsyncMenu = $('#btn-async-menu');
		this.$btnDeleteMenu = $('#btn-delete-menu');
		this.$btnSave = $('#btn-save');
		this.$btnPublish = $('#btn-publish');
	};

	Page.prototype.init = function() {
		this.loadPlugins();
		this.btnAsyncMenuEvent();
		this.btnDeleteMenuEvent();
		this.menuEditModalListen();
		this.menuDeleteEvent();
		this.btnSaveEvent();
		this.btnPublishEvent();
    };
    
    Page.prototype.loadPlugins = function(){
    	//生成右侧菜单
    	$('#menu').nestable({
    		maxDepth: 2
    	});
    	
    	$('.ladda-button').ladda();
    };
    
    /**
     * 菜单同步点击事件
     */
    Page.prototype.btnAsyncMenuEvent = function(){
    	var $this = this;
    	$this.$btnAsyncMenu.click(function(){
    		$this.$btnAsyncMenu.ladda('start');
    		$.ajax({
    			type: 'post',
    			url: contextPath + '/admin/mp/menu/async',
    			dataType: 'json',
    			success: function(result){
    				$this.$btnAsyncMenu.ladda('stop');
    				if(result.success){
    					$.Notification.notify('custom','top center', '通知', '同步请求成功');
    					setTimeout(() => {
    						window.location.reload();
    					}, 1000);
    				} else {
    					$.Notification.notify('error','top center', '通知', result.message);
    				}
    			}
    		});
    	});
    },
    
    /**
     * 删除菜单点击事件
     */
    Page.prototype.btnDeleteMenuEvent = function(){
    	var $this = this;
    	$this.$btnDeleteMenu.click(function(){
    		swal({
                title: '确定删除吗？',
                text: "删除微信公众号所有菜单",
                type: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4fa7f3',
                cancelButtonColor: '#d57171',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(function () {
            	$this.$btnDeleteMenu.ladda('start');
            	$.ajax({
        			type: 'post',
        			url: contextPath + '/admin/mp/menu/delete',
        			dataType: 'json',
        			success: function(result){
        				$this.$btnDeleteMenu.ladda('stop');
        				if(result.success){
        					swal('操作完成', '微信菜单已删除，请查看手机微信公众号', 'success');
        				} else {
        					swal('删除失败', result.message, 'error');
        				}
        			}
        		});
            });
    	});
	},
	
	/**
	 * 弹出框监听
	 */
	Page.prototype.menuEditModalListen = function(){
		var $this = this;
		$('#menu-edit-modal').on('show.bs.modal', function (e) {
			var data = $(e.relatedTarget).closest('li').data();
			//还原样式
			$('.modal-body .col-md-12', this).show();
			$('input,select', this).prop('readonly', false);
			$('#menu-edit-modal-save', this).show();
			$('input,select', this).val('');
			
			if($(e.relatedTarget).hasClass('menu-search')){
				$('.modal-title', this).text('查看');
				$('[name="name"]', this).val(data.name);
				$('[name="type"]', this).val(data.type);
				$('[name="key"]', this).val(data.key);
				$('[name="url"]', this).val(data.url);
				if(data.key){
					$('[name="key"]', this).closest('.col-md-12').show();
				} else {
					$('[name="key"]', this).closest('.col-md-12').hide();
				}
				if(data.url){
					$('[name="url"]', this).closest('.col-md-12').show();
				} else {
					$('[name="url"]', this).closest('.col-md-12').hide();
				}
				$('input,select', this).prop('readonly', true);
				$('#menu-edit-modal-save', this).hide();
			} else if($(e.relatedTarget).hasClass('menu-edit')){
				$('.modal-title', this).text('修改');
				$('[name="name"]', this).val(data.name);
				$('[name="type"]', this).val(data.type);
				$('[name="key"]', this).val(data.key);
				$('[name="url"]', this).val(data.url);
				$('#menu-edit-modal-save', this).unbind().click(function(){
					$this.editSaveFn(e.relatedTarget);
				});
			} else {
				$('.modal-title', this).text('添加');
				$('#menu-edit-modal-save', this).unbind().click(function(){
					$this.addSaveFn(e.relatedTarget);
				});
			}
		});
	},
	
	/**
	 * 菜单删除按钮点击事件
	 */
	Page.prototype.menuDeleteEvent = function(){
		$('.menu-delete', '#menu').on('click', function(){
			$(this).closest('li').remove();
		});
	},
	
	/**
	 * 保存按钮点击事件
	 */
	Page.prototype.btnSaveEvent = function(){
		var $this = this;
		$this.$btnSave.click(function(){
			$this.$btnSave.ladda('start');
			var $form = $this.gatherForm();
			$.ajax({
				type: 'post',
				url: contextPath + '/admin/mp/menu/save',
				data: JSON.stringify($form),
				contentType: 'application/json',
				dataType: 'json',
				success: function(result){
					$this.$btnSave.ladda('stop');
					if(result.success){
						$.Notification.notify('custom','top center', '通知', '保存成功');
						setTimeout(() => {
							window.location.reload();
						}, 1000);
					} else {
						$.Notification.notify('error','top center', '通知', result.message);
					}
				}
			});
		});
	};
	
	/**
	 * 发布按钮点击事件
	 */
	Page.prototype.btnPublishEvent = function(){
		var $this = this;
		$this.$btnPublish.click(function(){
			swal({
	            title: '确定发布吗？',
	            text: "此操作是将本地数据同步到微信菜单",
	            type: 'question',
	            showCancelButton: true,
	            confirmButtonColor: '#4fa7f3',
	            cancelButtonColor: '#d57171',
	            confirmButtonText: '确定',
	            cancelButtonText: '取消'
	        }).then(function () {
	        	$this.$btnPublish.ladda('start');
	        	$.ajax({
	    			type: 'post',
	    			url: contextPath + '/admin/mp/menu/publish',
	    			dataType: 'json',
	    			success: function(result){
	    				$this.$btnPublish.ladda('stop');
	    				if(result.success){
	    					swal('操作完成', '微信菜单已发布，请查看手机微信公众号', 'success');
	    				} else {
	    					swal('发布失败', result.message, 'error');
	    				}
	    			}
	    		});
	        });
		});
	},
	
	/**
	 * 新增生成菜单模板
	 * @param data 数据
	 * @param isol 是否含有第二级
	 */
	Page.prototype.addTmpl = function(data, isol){
		var html = [];
		html.push('<li class="dd-item dd3-item">');
		html.push(' <div class="dd-handle dd3-handle"></div>');
		html.push(' <div class="dd3-content">');
		html.push('  <span class="name-text"></span>');
		html.push('  <div class="pull-right">');
		html.push('   <a class="menu-search" href="#" data-toggle="modal" data-target="#menu-edit-modal"><i class="fa fa-search"></i></a>');
		html.push('   <a class="menu-add" href="#" data-toggle="modal" data-target="#menu-edit-modal"><i class="fa fa-plus"></i></a>');
		html.push('   <a class="menu-edit" href="#" data-toggle="modal" data-target="#menu-edit-modal"><i class="fa fa-pencil"></i></a>');
		html.push('   <a class="menu-delete" href="#"><i class="fa fa-trash-o"></i></a>');
		html.push('  </div>');
		html.push(' </div>');
		html.push('</li>');
		
		var $li = $(html.join(' '));
		for ( var key in data) {
			if(data[key]){
				$li.attr('data-'+key, data[key]);
			}
		}
		if(data.name){
			$('.name-text', $li).text(data.name);
		}
		
		if(isol){
			var $ol = $('<ol class="dd-list"></ol>');
			$ol.append($li);
			return $ol;
		}
		return $li;
	},
	
	/**
	 * 弹出框新增保存方法
	 */
	Page.prototype.addSaveFn = function(target){
		var $this = this;
		var $modal = $('#menu-edit-modal'), data = {};
		data.name = $('[name="name"]', $modal).val();
		data.type = $('[name="type"]', $modal).val();
		data.key = $('[name="key"]', $modal).val();
		data.url = $('[name="url"]', $modal).val();
		var $parent = $(target).parents('li').last();
		
		//添加一级节点时会出现此情况
		if($parent.length == 0){
			if($('#menu').children('ol').length > 0){
				$('#menu').children('ol').append($this.addTmpl(data, false));
			} else {
				$('#menu').append($this.addTmpl(data, true));
			}
		}
		
		//查找ol>0表示含有子节点
		if($parent.children('ol').length > 0){
			$parent.children('ol').append($this.addTmpl(data, false));
		} else {
			var expand = '<button data-action="collapse" type="button" style="display: block;">Collapse</button>'
					   + '<button data-action="expand" type="button" style="display: none;">Expand</button>';
			$parent.prepend(expand);
			$parent.append($this.addTmpl(data, true));
		}
		$modal.modal('hide');
	},

	/**
	 * 弹出框编辑保存方法
	 */
	Page.prototype.editSaveFn = function(target){
		var $modal = $('#menu-edit-modal'), data = {};
		data.name = $('[name="name"]', $modal).val();
		data.type = $('[name="type"]', $modal).val();
		data.key = $('[name="key"]', $modal).val();
		data.url = $('[name="url"]', $modal).val();
		var $li = $(target).closest('li');
		for ( var key in data) {
			if(data[key]){
				$li.attr('data-'+key, data[key]);
			}
		}
		if(data.name){
			$($li.find('.name-text')[0]).text(data.name);
		}
		$li.data(data);
		$modal.modal('hide');
	},
	
	/**
	 * 收集菜单数据
	 */
	Page.prototype.gatherForm = function(){
		var $parents = $('#menu > ol > li');
		var data = [];
		$parents.each(function(i, parent){
			var pdata = $(parent).data();
			var $childs = $('ol > li', parent);
			if($childs.length > 0){
				pdata.subButtons = [];
				$childs.each(function(j, child){
					pdata.subButtons.push($(child).data());
				});
			}
			data.push(pdata);
		});
		return data;
	},
	
    // init
	$.Page = new Page, $.Page.Constructor = Page;
})(jQuery);

$(function(){
	$.Page.init();
});
